const fs = require('fs');
const path = require('path');

// 创建文件夹和文件的方法
const createdbModelFile = (dirname, filename) => {
    const directoryPath = path.join('./model', dirname);
    const filePath = path.join(directoryPath, filename);
    // 创建目录
    fs.mkdir(directoryPath, { recursive: true }, (err) => {
        if (err) {
            console.error('Error creating directory:', err);
        } else {
            console.log(`Directory '${dirname}' created successfully.`);
            // 创建文件
            fs.writeFile(filePath, '', (err) => {
                if (err) {
                    console.error('Error creating file:', err);
                } else {
                    console.log(`File '${filename}' created successfully in '${dirname}' directory.`);
                }
            });
        }
    });
};

// 自动导入路由函数
function autoImportRoutes(app, directory) {
    fs.readdirSync(directory).forEach(file => {
        const routePath = path.join(directory, file);
        const route = require(routePath);
        let routeName = file.split('.')[0] || ''; // 提取文件名，去除文件扩展名
        app.use(`/${routeName}`, route);
    });
}

// 格式化数据返回
// 中间件函数，用于返回统一格式的响应
const formatResponse = (req, res, next) => {
    res.apiSuccess = (message, data) => {
        res.send({
            code: 200,
            success: true,
            message,
            data
        });
    };

    res.apiError = (message, data) => {
        res.send({
            code: 400,
            success: false,
            error: message,
            data
        });
    };

    next();  // 继续执行下一个中间件
};


// // 指定路由文件所在的目录
// const routesDirectory = path.join(__dirname, './router');
// //
// // // 调用自动导入路由函数
// // autoImportRoutes(routesDirectory);


module.exports = {
    autoImportRoutes, createdbModelFile, formatResponse
}